package service

import (
	"duoke/model"
	"duoke/tables"
	"duoke/utils/orm"
	"errors"
	"github.com/gin-gonic/gin"
)

var Store = new(storeService)

type storeService struct{}

func (s *storeService) GetById(c *gin.Context, id int, field string) (*tables.Store, error) {
	accountR, _ := Request.Account(c)
	data := new(tables.Store)
	has, err := orm.Db.Where("acid =?", accountR.Id).ID(id).Cols(field).Get(data)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, errors.New("该记录不存在")
	}
	return data, nil
}

func (s *storeService) List(c *gin.Context, req model.ReqList) ([]tables.Store, error) {
	accountR, _ := Request.Account(c)
	list := make([]tables.Store, 0)
	query := orm.Db.Where("acid =?", accountR.Id).Desc("id")
	if req.Keyword != "" {
		query = query.Where("name =?", req.Keyword)
	}
	err := query.Find(&list)
	if err != nil {
		return nil, err
	}
	return list, nil
}
func (s *storeService) Save(c *gin.Context, req model.ReqStore) error {
	accountR, _ := Request.Account(c)
	if req.Id > 0 {
		_, err := s.GetById(c, req.Id, "")
		if err != nil {
			return err
		}
		// 保存数据
		_, err = orm.Db.ID(req.Id).Cols("name", "img", "address", "hours", "tel", "location").Update(req)
		if err != nil {
			return err
		}
	} else {
		// 保存数据
		req.Acid = accountR.Id
		_, err := orm.Db.Insert(req)
		if err != nil {
			return err
		}
	}
	return nil
}
func (s *storeService) Del(c *gin.Context, req model.ReqIds) error {
	accountR, _ := Request.Account(c)
	_, err := orm.Db.Where("acid =?", accountR.Id).
		In("id", req.Ids).
		Delete(new(tables.Store))
	if err != nil {
		return err
	}
	return nil
}
